package com.frogs.ucenter.service.impl;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.FavoriteService;

@Service("favoriteService")
public class FavoriteServiceImpl extends GoodsBaseServiceImpl implements FavoriteService {
	
	private static Logger log = LoggerFactory.getLogger(FavoriteServiceImpl.class);

	/**
	 * 获取收藏列表
	 */
	@Override
	public PageList<Map<String,Object>> getFavoriteList(Integer pageNo, Integer pageSize, Integer userId)  throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_FAVORITE_LIST");
		String[] otherParams = {ApiUrlParamEnum.pageNo.getParamName(),pageNo.toString(),
								ApiUrlParamEnum.pageSize.getParamName(),pageSize.toString(),
								ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			
			JSONArray listJSONArray = jsonObjectResult.getJSONObject("response").getJSONArray("list");
			if (listJSONArray != null) {
				Map<Integer, JSONObject> goodsMap = super.getGoodsMap(listJSONArray);
		    	result.addAll(super.mergeGoods(listJSONArray, goodsMap));
			}
	    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
	    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
		} catch (IllegalStateException e) {
			log.error("func[getFavoriteList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取收藏列表接口异常！");
		}
		return result;
	}

	/**
	 * 获取单个收藏信息
	 */
	@Override
	public JSONObject showFavorite(Integer userId, Integer favoriteId)  throws Exception {
		return null;
	}

	@Override
	public JSONObject deleteFavorite(Integer userId, Integer favoriteId)  throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_FAVORITE_DELETE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
				ApiUrlParamEnum.userGoodsFavoriteId.getParamName(),favoriteId.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[deleteFavorite] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取单个收藏信息接口异常！");
		}
		
		return result;
	}

	@Override
	public JSONObject addFavorite(Integer userId, Integer originalGoodsId,
			String tagIds, String favoriteTag, Integer goodsId, Integer mealId,
			Integer isPrivacy, Integer status, String remark)
			throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_FAVORITE_ADD");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.originalGoodsId.getParamName(), originalGoodsId.toString(),
				ApiUrlParamEnum.tagIds.getParamName(), tagIds,
				ApiUrlParamEnum.isPrivacy.getParamName(), isPrivacy.toString(),
				ApiUrlParamEnum.status.getParamName(), status.toString(),
				ApiUrlParamEnum.remark.getParamName(), remark,
				ApiUrlParamEnum.goodsId.getParamName(), goodsId.toString(),
				ApiUrlParamEnum.mealId.getParamName(), mealId.toString(),
				ApiUrlParamEnum.applicablePlatformId.getParamName(), String.valueOf(ApplicablePlatformEnum.WEB.getId()),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			return result;
		} catch (IllegalStateException e) {
			log.error("func[addFavorite] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("添加收藏信息接口异常！");
		}
		
		return result;
	}

}
